package com.yitao.cms.service.shopInfo;

import com.google.common.collect.Lists;
import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.json.JSON;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.constant.ShopEnums;
import com.yitao.client.dto.shopInfo.ShopInfoDto;
import com.yitao.client.model.shopInfo.QShopInfoModel;
import com.yitao.client.model.shopInfo.ShopConfigModel;
import com.yitao.client.model.shopInfo.ShopInfoModel;
import com.yitao.client.model.user.BuyerUserModel;
import com.yitao.cms.constant.BaseEnum;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.service.user.cmsUser.OperationUserService;
import com.yitao.cms.service.user.rollinUser.BuyerUserService;
import com.yitao.cms.utils.BaseUtils;
import com.yitao.cms.vo.ShopInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class CmsShopInfoService extends GenericEntityService<ShopInfoModel, ShopInfoDto, QShopInfoModel> {
    public CmsShopInfoService(EntityManager entityManager) {
        super(entityManager);
    }

    private BaseUtils base = BaseUtils.getInstance();

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperationUserService operationUserService;

    @Autowired
    private BuyerUserService buyerUserService;

    @Autowired
    private ShopConfigService shopConfigService;

    @Autowired
    private ShopPaymentMethodService shopPaymentMethodService;

    // 店铺展示分类数量 默认5个
    public static final Integer CATEGORYNUM = 5;

    /**
     * 店铺ID查询店铺详情
     *
     * @param shopId
     * @return
     */
    public ShopInfoDto getShopInfoById(Long shopId) {
        ShopInfoModel shopInfoModel = queryFactory.select(Q).from(Q).where(Q.id.eq(shopId)).fetchOne();
        ShopInfoDto shopInfoDto = null;
        if (shopInfoModel != null) {
            shopInfoDto = new ShopInfoDto();
            BeanUtils.copyProperties(shopInfoModel, shopInfoDto);
            if (shopInfoModel.getOverseasUser()==null){
                shopInfoDto.setOverseasUser(false);
            }
            if (shopInfoModel.getInsuranceStatus()==null){
                shopInfoDto.setInsuranceStatus(false);
            }
        }
        return shopInfoDto;
    }

    /**
     * 店铺ID查询店铺详情
     *
     * @param shopId
     * @return
     */
    public ShopInfoVo getShopInfoVoById(Long shopId) {
        ShopInfoDto shopInfoDto = getShopInfoById(shopId);
        ShopInfoVo shopInfoVo = new ShopInfoVo();
        if(shopInfoDto != null) {
            BeanUtils.copyProperties(shopInfoDto, shopInfoVo);
            // 处理返回的支付方式，如果支付方式为空或者为null，默认返回微信支付和银行卡支付
            List<Integer> shopPaymentMethodList = shopPaymentMethodService.findShopPaymentMethodByShopId(shopId);
            if(shopPaymentMethodList == null || shopPaymentMethodList.size() == 0) {
                shopPaymentMethodList.add(ShopEnums.SHOP_PAYMENT_METHOD.WE_CHAT.getCode());
                shopPaymentMethodList.add(ShopEnums.SHOP_PAYMENT_METHOD.BANK_CARD.getCode());
            }
            shopInfoVo.setPaymentCodeList(shopPaymentMethodList);
        }
        return shopInfoVo;
    }

    /**
     *
     * @return
     */
    public List<ShopInfoModel> getShopInfo() {
        List<ShopInfoModel> list =  repository.findAll(PredicateBuilder.conjunction().get());
        return list;
    }

    /**
     * 查询店铺店铺列表
     */
    public PagedOutput<ShopInfoVo> getListByBean(ShopInfoDto shopInfoDto, PagedInput pagedInput) {
        List<ShopInfoVo> shopInfoDtoList = Lists.newArrayList();
        PagedOutput<ShopInfoModel> mallOrderModelPagedOutput = repository.pagingList(PredicateBuilder.conjunction().
                ifNotNullThenAnd(shopInfoDto.getId(), () -> Q.id.in(shopInfoDto.getId())).
                ifHasTextThenAnd(shopInfoDto.getShopName(), () -> Q.shopName.contains(shopInfoDto.getShopName())).
                ifNotNullThenAnd(shopInfoDto.getUserId(), () -> Q.userId.in(shopInfoDto.getUserId())).
                ifHasTextThenAnd(shopInfoDto.getShopPhone(), () -> Q.shopPhone.notIn(shopInfoDto.getShopPhone())).
                        get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.createTime));
        if (mallOrderModelPagedOutput != null && mallOrderModelPagedOutput.getData() != null && mallOrderModelPagedOutput.getData().size() != 0) {
            List<ShopInfoModel> shopInfoModelList = mallOrderModelPagedOutput.getData();
            ShopInfoVo shopInfoVo = null;
            for (ShopInfoModel shopInfoModel : shopInfoModelList) {
                shopInfoVo = new ShopInfoVo();
                BeanUtils.copyProperties(shopInfoModel, shopInfoVo);
                //补充店铺关联门店二维码
                if (shopInfoModel.getId()!=null){
                    ShopConfigModel shopConfigModel = shopConfigService.findShopConfigByShopId(shopInfoModel.getId());
                    if (shopConfigModel!=null){
                        shopInfoVo.setServerCodeUrl(shopConfigModel.getServerCodeUrl());
                    }
                }
                //补充创建人
                if (shopInfoModel.getCreateBy() != null) {
                    OperationUserCmsModel userModel = operationUserService.findUserInfoById(shopInfoModel.getCreateBy());
                    if (userModel != null) {
                        shopInfoVo.setCreateBy(userModel.getUserName());
                    }
                }
                //用户类型
                if (shopInfoModel.getOverseasUser()==null){
                    shopInfoVo.setOverseasUser(false);
                }
                // 是否购买保险
                if (shopInfoModel.getInsuranceStatus()==null){
                    shopInfoDto.setInsuranceStatus(false);
                }
                shopInfoDtoList.add(shopInfoVo);
            }

        }
        return new PagedOutput<>(pagedInput, mallOrderModelPagedOutput.getTotalElements(), shopInfoDtoList);
    }


    /**
     * 添加修改店铺
     */
    @Transactional
    public DataOutput addOrUpdateByBean(ShopInfoVo shopInfoVo) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        if (shopInfoVo.getOverseasUser()==null){
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(),"客户类型不能为空!");
        }
        logger.info("添加修改店铺{}", JSON.toJSONString(shopInfoVo));
        Date date = new Date();
        ShopInfoModel shopInfoModelAdd = null;
        if (shopInfoVo != null) {
            Boolean insuranceStatus = shopInfoVo.getInsuranceStatus();
            if(insuranceStatus == null) {
                shopInfoVo.setInsuranceStatus(false);
            }
            shopInfoModelAdd = new ShopInfoModel();
            if (shopInfoVo.getId() != null) {
                ShopInfoModel shopInfoModel = queryFactory.select(Q).from(Q).where(Q.id.eq(shopInfoVo.getId())).fetchOne();
                if (shopInfoModel != null) {
                    BeanUtils.copyProperties(shopInfoVo, shopInfoModelAdd);
                    shopInfoModelAdd.setCreateBy(shopInfoModel.getCreateBy());
                    shopInfoModelAdd.setCreateTime(shopInfoModel.getCreateTime());
                    shopInfoModelAdd.setIsDelete(shopInfoModel.getIsDelete());
                    shopInfoModelAdd.setUserId(userSession.getId());
                    shopInfoModelAdd.setLastUpdateBy(userSession.getId());
                    shopInfoModelAdd.setLastUpdateTime(date);
                    // 2020.03.03 店铺展示分类数量
                    shopInfoModelAdd.setCategoryNum(shopInfoModel.getCategoryNum());
                }
            } else {
                BeanUtils.copyProperties(shopInfoVo, shopInfoModelAdd);
                shopInfoModelAdd.setShopStatus(BaseEnum.YesOrNoEnum.NO.getCode());
                shopInfoModelAdd.setCreateBy(userSession.getId());
                shopInfoModelAdd.setCreateTime(date);
                shopInfoModelAdd.setLastUpdateTime(date);
                shopInfoModelAdd.setUserId(userSession.getId());
                shopInfoModelAdd.setLastUpdateBy(userSession.getId());
                shopInfoModelAdd.setIsDelete(BaseEnum.YesOrNoEnum.NO.getCode());
                // 2020.03.03 店铺展示分类数量,新增时默认设置为5个
                shopInfoModelAdd.setCategoryNum(CATEGORYNUM);
            }
            ShopInfoModel save = repository.save(shopInfoModelAdd);
            // 获取店铺的支付方式
            List<Integer> paymentCodeList = shopInfoVo.getPaymentCodeList();
            if (save != null && save.getId() != null) {
                int i = shopPaymentMethodService.addPayment(paymentCodeList, save.getId(), userSession.getId());

                OperationUserCmsModel operationUserCmsModel = new OperationUserCmsModel();
                operationUserCmsModel.setLastUpdateTime(date);
                operationUserCmsModel.setId(userSession.getId());
                operationUserCmsModel.setShopId(save.getId());
                operationUserService.updateUser(operationUserCmsModel);//更新session信息
                if (shopInfoVo.getId() == null) {//新增就添加买手版用户信息
                    OperationUserCmsModel userInfoById = operationUserService.findUserInfoById(userSession.getId());
                    BuyerUserModel buyerUserModel = new BuyerUserModel();
                    buyerUserModel.setShopId(save.getId());
                    buyerUserModel.setAvatarPath(save.getShopLogo());
                    buyerUserModel.setBalanceAmount(0L);
                    buyerUserModel.setOperationUserId(userInfoById.getId());
                    buyerUserModel.setPhone(userInfoById.getPhone());
                    buyerUserModel.setUserName(userInfoById.getUserName());
                    buyerUserModel.setPassWord(userInfoById.getPassword());
                    buyerUserService.insertBuyerUserInfo(buyerUserModel);
                }
                return base.getSuccessMsg(getShopInfoVoById(save.getId()));
            }
        }
        return base.getErrorMsg();
    }

    /**
     * 店铺设置首页展示分类数量
     *
     * @param categoryNum 展示数量
     * @param request
     * @return
     */
    @Transactional
    public DataOutput updateCategoryNum(String categoryNum, HttpServletRequest request) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        logger.info("设置的展示数量为:" + categoryNum);
        if(StringUtils.isBlank(categoryNum) || "null".equals(categoryNum)) {
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "设置的参数不能为空");
        }
        Long shopId = userSession.getShopId();
        if(shopId == null) {
            return new DataOutput(CommonStatus.NOT_FOUND.getCode(), "当前用户没有绑定店铺");
        }
        repository.updateByWhere(PredicateBuilder.conjunction().and(() -> Q.id.eq(shopId)).get(),
                it -> it.set(Q.categoryNum, Integer.valueOf(categoryNum)));
        return new DataOutput();
    }

    /**
     * 功能描述: 获取店铺当前设置的首页展示运营分类数量
     *
     * @param request
     *
     * @return
     * @auther Kien
     * @date 2020/3/3 15:09
     */
    public DataOutput updateCategoryNum(HttpServletRequest request) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        Long shopId = userSession.getShopId();
        if(shopId == null) {
            return new DataOutput(CommonStatus.NOT_FOUND.getCode(), "当前用户没有绑定店铺");
        }
        ShopInfoModel shopInfoModel = repository.findOne(PredicateBuilder.conjunction().and(() -> Q.id.eq(shopId)).get());
        if(shopInfoModel == null) {
            return new DataOutput(CommonStatus.NOT_FOUND.getCode(), "根据店铺id未获取道店铺信息");
        }
        Integer categoryNum = shopInfoModel.getCategoryNum();
        if(categoryNum == null) {
            categoryNum = CATEGORYNUM; // 如果为空，默认设置为5
        }
        return new DataOutput(categoryNum);
    }
}
